#ifndef CODEEDITOR_H
#define CODEEDITOR_H


#include <QPlainTextEdit>
#include <QObject>
#include "syntaxhighlighter.h"
#include <QStack>
#include <QPixmap>
#include <QLabel>

class QPaintEvent;
class QResizeEvent;
class QSize;
class QWidget;
class SyntaxHighlighter;

class LineNumberArea;
class MainWindow;

class CodeEditor : public QPlainTextEdit
{
    Q_OBJECT

public:
    CodeEditor(QWidget *parent = nullptr, MainWindow *mainWindowHandler = nullptr);

    void lineNumberAreaPaintEvent(QPaintEvent *event);
    int lineNumberAreaWidth();
    QString filenameThis;
    SyntaxHighlighter *syntaxHighlighter;

    int blockNumberAt(int y);

    void loadBackgroundImage(QString imagePath, qreal opacity1);
    void setBackgroundImage(const QString &imagePath);
    void setBackgroundOpacity(qreal newOpacity);

protected:
    void resizeEvent(QResizeEvent *event) override;
    void keyPressEvent(QKeyEvent *event) override;
    void paintEvent(QPaintEvent *event) override;
    void wheelEvent(QWheelEvent *event) override;

private slots:
    void updateLineNumberAreaWidth(int newBlockCount);
    //void highlightCurrentLine();
    void updateLineNumberArea(const QRect &rect, int dy);
    void highlightMatchingBrackets();

private:
    MainWindow *mainWindow;
    QWidget *lineNumberArea;
    QList<QTextEdit::ExtraSelection> bracketSelections;

    // 新添加的私有方法
    void highlightBracket(int position);
    bool isBracket(QChar ch);
    bool isOpeningBracket(QChar ch);
    QChar getMatchingBracket(QChar bracket);

    void autoCompleteBracket(QKeyEvent *event);
    void handleNewLine();

    QPixmap *backgroundImage = nullptr;
    qreal opacity = 0.5;
    QLabel la;
};


class LineNumberArea : public QWidget
{
public:
    LineNumberArea(CodeEditor *editor) : QWidget(editor) {
        codeEditor = editor;
        this->setMouseTracking(true);
    }

    QSize sizeHint() const override{
        return QSize(codeEditor->lineNumberAreaWidth(), 0);
    }

protected:
    void paintEvent(QPaintEvent *event) override{
        codeEditor->lineNumberAreaPaintEvent(event);
    }
    void mouseMoveEvent(QMouseEvent *event) override;
    void mousePressEvent(QMouseEvent *event) override;

private:
    CodeEditor *codeEditor;
};

#endif // CODEEDITOR_H
